/*******************************************************************************
 * Copyright (C) 2010 4Point Solutions Ltd. www.4point.com
 * 
 * Portions based on PushButton Engine, 
 * (C) 2009 PushButton Labs, LLC www.pushbuttonengine.com
 * 
 * This file is licensed under the terms of the MIT license, which is included
 * in the license.txt file at the root of this project.
 ******************************************************************************/
package com.fourpointsolutions.flex.utils.logging
{
	import flash.events.KeyboardEvent;
	
	import mx.core.Application;
	import mx.managers.SystemManager;

	/**
	 * LogAppender for displaying log messages in a LogViewer. The LogViewer will be
     * attached and detached from the main view when the defined hot key is pressed. The tilde (~) key 
	 * is the default hot key.
	 */	
	public class UIAppender implements ILogAppender
	{ 
		protected static var _hotKey:uint;
		protected var _logViewer:LogViewer;
	    
		public function UIAppender()
		{
		    var manager:SystemManager = Application.application.systemManager;
		    manager.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			
			_hotKey = LoggerUtils.TILDE_KEY_CODE;
			_logViewer = new LogViewer();
		}
  
		private function onKeyDown(event:KeyboardEvent):void
		{
		    // Only pop up the console in LOGGER_UI_MODE
		    if (Logger.loggingMode == Logger.LOGGER_UI_MODE) {
    			if (event.keyCode != _hotKey)
    				return;
    			 
    			if(_logViewer)
    			{
    				if (_logViewer.parent)
    				{
    					_logViewer.parent.removeChild(_logViewer);
    					_logViewer.deactivate();
    				}
    				else
    				{
    					Application.application.systemManager.stage.addChild(_logViewer);
    					_logViewer.activate();
    				}
			}
		    }
		}
  
		public function addLogMessage(level:String, loggerName:String, message:String):void
		{
			if(_logViewer)
			_logViewer.addLogMessage(level, loggerName, message);
		}
		
		/**
		 * The keycode to toggle the UIAppender interface.
		 */		
		public static function set hotKey(value:uint):void
		{
			Logger.print(UIAppender, "Setting hotKey to: "+value);
			_hotKey = value;
		}
		
		/**
		 * Removes the hotkey listener from the stage.
		 */
		public function destroyListener():void {
		    var manager:SystemManager = Application.application.systemManager;
            manager.stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
            
            try {
                if (_logViewer && manager.stage.getChildIndex(_logViewer) >= 0) {
                    manager.stage.removeChild(_logViewer);
                }
            } catch (error:ArgumentError) {
                trace("LogAppender was never added to the stage.");
            }
            _logViewer = null;
		}
	}
}